<template>
  <div class="collection-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h2 class="page-title">我的合集管理</h2>
      <a-button type="primary" class="create-btn" @click="openCreateModal">
        <template #icon><PlusOutlined/></template>
        新建合集
      </a-button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <a-select
          v-model:value="statusFilter"
          placeholder="合集状态"
          style="width: 150px; margin-right: 10px"
          @change="handleFilterChange"
      >
        <a-select-option value="">全部状态</a-select-option>
        <a-select-option value="1">开放</a-select-option>
        <a-select-option value="2">隐藏</a-select-option>
      </a-select>

      <a-input
          v-model:value="searchKeyword"
          placeholder="搜索合集名称"
          style="width: 200px"
          allow-clear
          @pressEnter="handleSearch"
      >
        <template #suffix>
          <SearchOutlined @click="handleSearch" />
        </template>
      </a-input>
    </div>

    <!-- 合集列表 -->
    <div class="collections-container">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <Spin size="large" tip="加载中..." />
      </div>

      <!-- 空状态 -->
      <div v-else-if="collections.length === 0" class="empty-container">
        <Empty description="暂无合集数据" />
        <a-button type="primary" style="margin-top: 16px" @click="openCreateModal">
          新建第一个合集
        </a-button>
      </div>

      <!-- 列表内容 -->
      <div v-else class="collections-grid">
        <div class="collection-card" v-for="(collection, index) in collections" :key="collection.id" @click="openDetail(collection)">
          <div class="collection-status" :class="getStatusClass(collection.status)">
            {{ getStatusText(collection.status) }}
          </div>

          <img :src="getCoverUrl(collection.coverUrl)" alt="合集封面" class="collection-cover" />

          <div class="collection-info">
            <h3 class="collection-title" :title="collection.name">{{ collection.name }}</h3>

            <p class="collection-desc" :title="collection.description">{{ collection.description }}</p>

            <div class="collection-meta">
              <span>
                <CalendarOutlined /> {{ formatDate(collection.createTime) }}
              </span>
            </div>

            <div class="collection-actions">
              <a-button size="small" @click.stop="editCollection(collection)">
                <EditOutlined /> 编辑
              </a-button>
              <a-button
                  size="small"
                  danger
                  @click.stop="handleDeleteConfirm(collection.id)"
              >
                <DeleteOutlined /> 删除
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控制器 -->
    <div class="pagination-container" v-if="total > 0 && !isLoading">
      <Pagination
          v-model:current="pageNum"
          :pageSize="pageSize"
          :total="total"
          show-size-changer
          show-quick-jumper
          :show-total="(total) => `共 ${total} 条记录`"
          @change="handlePageChange"
          @showSizeChange="handlePageSizeChange"
      />
    </div>

    <!-- 引入新建合集弹窗 -->
    <CollectionAddModel
        ref="createCollectionModal"
        @save="handleCreateCollection"
        @cancel="handleCancel"
    />

    <CollectionDetail
        :collection-id="selectedCollectionId"
        v-model:visible="isDetailVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message, Modal, Spin, Empty, Pagination } from 'ant-design-vue';
import {
  SearchOutlined, CalendarOutlined, PlusOutlined,
  EditOutlined, DeleteOutlined, FileTextOutlined
} from '@ant-design/icons-vue';
import CollectionAddModel from './CollectionAddModel.vue';
import { getCollectionList, deleteCollection } from '@/api/media/bizCollectionController';
import {getCollectionWorks} from "@/api/media/bizWorksController";
import CollectionDetail from "@/components/profile/CollectionDetail.vue";

// 分页查询参数类型（与后端接口匹配）
interface CollectionPageQuery {
  pageNum: number;        // 页码，从1开始
  pageSize: number;       // 每页条数
  name?: string;          // 合集名称（模糊查询）
  status?: number;        // 状态筛选
  userId?: number;        // 当前登录用户ID（如果需要）
}

// 分页结果类型
interface PageResult<T> {
  list: T[];              // 当前页数据列表
  total: number;          // 总记录数
  size: number;           // 每页条数
  current: number;        // 当前页码
  pages: number;          // 总页数
}


// 定义 BizCollection 类型（与子组件保持一致）
interface BizCollection {
  id: number;
  userId: number;
  name: string;
  coverUrl: string;
  description: string;
  status: number;
  createTime: string;
  updateTime: string;
}

// 定义 BizWorks 类型（与子组件保持一致）
interface BizWorks {
  id: number;
  worksName: string;
  coverFileUrl: string;
  duration: string;
  createTime: string;
  isCharge: number;
  status: number;
}

const isDetailVisible = ref(false);

const selectedCollectionId = ref<number>(0);

// 点击合集卡片打开详情的方法
const openDetail = (collection: BizCollection) => {
    console.log('点击了合集卡片，ID：', collection.id);
  selectedCollectionId.value = collection.id;
  isDetailVisible.value = true;
};
// 组件引用
const createCollectionModal = ref<InstanceType<typeof CollectionAddModel>>();

// 状态管理
const collections = ref<BizCollection[]>([]);
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const isLoading = ref(false);
const minioUrl = import.meta.env.VITE_MINIO_URL;

// 筛选条件
const statusFilter = ref('');
const searchKeyword = ref('');

// 页面加载时初始化
onMounted(async () => {
  await fetchCollectionsList();
});



// 获取合集列表
const fetchCollectionsList = async () => {
  try {
    isLoading.value = true;

    // 构建查询参数（匹配后端接口要求）
    const queryParams: CollectionPageQuery = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    };

    // 状态筛选
    if (statusFilter.value) {
      queryParams.status = Number(statusFilter.value);
    }

    // 名称搜索
    if (searchKeyword.value) {
      queryParams.name = searchKeyword.value;
    }

    // 调用后端接口
    console.log('请求参数:', queryParams);
    const response = await getCollectionList(queryParams);

    if (response.code === '00000' && response.data) {
      const pageResult: PageResult<BizCollection> = response.data;
      collections.value = pageResult.list || [];
      total.value = pageResult.total || 0;
    } else {
      message.error('获取合集列表失败: ' + (response.message || '未知错误'));
      collections.value = [];
    }
  } catch (error) {
    console.error('获取合集列表出错:', error);
    message.error('网络错误，获取合集列表失败');
  } finally {
    isLoading.value = false;
  }
};

// 分页变更处理
const handlePageChange = (page: number) => {
  pageNum.value = page;
  fetchCollectionsList();
};

// 每页条数变更处理
const handlePageSizeChange = (current: number, size: number) => {
  pageSize.value = size;
  pageNum.value = 1;
  fetchCollectionsList();
};

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1;
  fetchCollectionsList();
};

// 筛选条件变化处理
const handleFilterChange = () => {
  pageNum.value = 1;
  fetchCollectionsList();
};

// 打开新建合集弹窗
const openCreateModal = () => {
  createCollectionModal.value?.open();
};

// 处理创建合集成功
const handleCreateCollection = async () => {
  message.success('合集创建成功');
  await fetchCollectionsList(); // 刷新列表
};

// 取消操作
const handleCancel = () => {
  // 取消操作无需额外处理
};



const editCollection = async (collection: BizCollection) => {
  try {
    const works = await fetchCollectionWorks(collection.id);

    createCollectionModal.value?.open(true, {
      id: collection.id,
      name: collection.name,
      description: collection.description,
      cover: collection.coverUrl, // 直接使用后端返回的完整URL
      works: works || [],
      status: collection.status || 1
    });
  } catch (error) {
    console.error('获取合集作品失败:', error);
    message.error('无法加载合集作品数据');
  }
};

const fetchCollectionWorks = async (collectionId: number) => {
  // 调用API获取该合集下的作品列表
  console.log(collectionId);
  const response = await getCollectionWorks({
    collectionId: collectionId
  });
  if (response.code === '00000') {
    return response.data || [];
  }
  return [];
};
// 删除确认
const handleDeleteConfirm = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个合集吗？此操作不可撤销。',
    okText: '确认',
    cancelText: '取消',
    onOk: () => deleteSelectedCollection(id)
  });
};

// 删除合集
const deleteSelectedCollection = async (id: number) => {
  try {
    isLoading.value = true;
    await deleteCollection(id);
    message.success('删除成功');

    // 重新加载列表，如果当前页没数据了则返回上一页
    if (collections.value.length === 1 && pageNum.value > 1) {
      pageNum.value--;
    }
    await fetchCollectionsList();
  } catch (error) {
    console.error('删除合集失败:', error);
    message.error('删除失败，请重试');
  } finally {
    isLoading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString();
};

// 获取封面完整URL
const getCoverUrl = (coverUrl?: string) => {
return minioUrl + coverUrl;
};

// 状态文本映射
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '开放',
    2: '隐藏'
  };
  return statusMap[status] || '未知';
};

// 状态样式映射
const getStatusClass = (status: number) => {
  const classMap: Record<number, string> = {
    1: 'status-draft',
    2: 'status-review'
  };
  return classMap[status] || 'status-unknown';
};
</script>

<style scoped>
.collection-container {
  width: 100%;
  background: #0b2b5b;
  min-height: 600px;
  padding: 20px;
  color: #fff;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.create-btn {
  background: #2f80ed;
  border: none;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  flex-wrap: wrap;
}

/* 加载和空状态 */
.loading-container, .empty-container {
  width: 100%;
  padding: 80px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 合集网格布局 */
.collections-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

/* 合集卡片 */
.collection-card {
  background: #0f3a72;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  position: relative;
  cursor: pointer;
}

.collection-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

/* 合集状态标签 */
.collection-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  z-index: 1;
}

.collection-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.collection-info {
  display: flex;
  flex-direction: column;
}

.collection-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.collection-desc {
  font-size: 12px;
  color: #c9d8e9;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 32px;
}

.collection-meta {
  font-size: 12px;
  color: #9eb6d0;
  margin: 0 0 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.collection-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.collection-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: auto;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .filter-bar > * {
    width: 100% !important;
    margin-right: 0 !important;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .collections-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
</style>
